package com.gitee.srurl.core.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.gitee.srurl.core.exception.ServiceException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * rsa工具类
 *
 * @author zxw
 * @date 2023/5/3 14:39
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class RsaUtil {

    private static final RSA decryptRsa = new RSA(SpringContextUtil.getRequiredProperty("short-url.login.encrypt.private-key"), null);

    public static String decrypt(String params) {

        if (StrUtil.isBlank(params)) {
            throw new IllegalArgumentException("解密参数不能为空！");
        }
        try {
            byte[] decrypt = decryptRsa.decrypt(params, KeyType.PrivateKey);
            return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
        } catch (CryptoException e) {
            log.error("参数：{}，解密失败.", params);
            throw new ServiceException("参数解密失败！");
        }
    }
}
